<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>智能研究助理 | 多代理协作平台</title>
    <script src="./libs/tailwindcss.js"></script>
    <link href="./libs/font-awesome@4.7.0.min.css" rel="stylesheet" />
    <script src="./libs/chart@4.4.8.umd.min.js"></script>

    <!-- Tailwind 配置 -->
    <script>
      tailwind.config = {
        theme: {
          extend: {
            colors: {
              primary: "#165DFF",
              "primary-agent": "#3498db" /* 协调员蓝色 */,
              "research-agent": "#2ecc71" /* 搜索专家绿色 */,
              "analysis-agent": "#9b59b6" /* 分析专家紫色 */,
              "qa-agent": "#e74c3c" /* 质量保证红色 */,
              "writing-agent": "#f39c12" /* 写作专家橙色 */,
              "streaming-text": "#2c3e50",
              "background-light": "#f8f9fa",
              "border-color": "#e9ecef",
            },
            fontFamily: {
              sans: ["Inter", "sans-serif"],
              mono: ["Fira Code", "monospace"],
            },
          },
        },
      };
    </script>

    <style type="text/tailwindcss">
      @layer utilities {
        .content-auto {
          content-visibility: auto;
        }
        .scrollbar-hide {
          -ms-overflow-style: none;
          scrollbar-width: none;
        }
        .scrollbar-hide::-webkit-scrollbar {
          display: none;
        }
        .typewriter-text {
          overflow: hidden;
          border-right: 0.15em solid #165dff;
          white-space: pre-wrap;
          margin: 0 auto;
          animation: blink-caret 0.75s step-end infinite;
        }
        .agent-pulse {
          animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
        }
        .gradient-border {
          position: relative;
          border-radius: 0.5rem;
        }
        .gradient-border::before {
          content: "";
          position: absolute;
          inset: -2px;
          z-index: -1;
          border-radius: 0.6rem;
          background: linear-gradient(90deg, var(--tw-gradient-stops));
        }
      }

      @keyframes blink-caret {
        from,
        to {
          border-color: transparent;
        }
        50% {
          border-color: #165dff;
        }
      }

      @keyframes pulse {
        0%,
        100% {
          opacity: 1;
        }
        50% {
          opacity: 0.5;
        }
      }

      .timeline-connector {
        @apply absolute w-0.5 bg-gray-200 z-0;
        left: 12px;
        top: 20px;
        bottom: 150px;
      }

      .agent-card {
        transition: all 0.3s ease;
      }

      .agent-card:hover {
        transform: translateY(-3px);
        box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1),
          0 10px 10px -5px rgba(0, 0, 0, 0.04);
      }

      .progress-bar {
        transition: width 1s ease-in-out;
      }

      .slide-in {
        animation: slideIn 0.5s ease forwards;
      }

      @keyframes slideIn {
        from {
          transform: translateX(-20px);
          opacity: 0;
        }
        to {
          transform: translateX(0);
          opacity: 1;
        }
      }

      /* 全屏样式 */
      .fullscreen {
        position: fixed;
        top: 0;
        left: 0;
        width: 100vw;
        height: 100vh;
        background: white;
        z-index: 9999;
        overflow: auto;
      }
    </style>
  </head>

  <body
    class="bg-background-light font-sans text-gray-800 antialiased min-h-screen flex flex-col overflow-hidden"
  >
    <!-- 顶部操作栏 -->
    <header class="bg-white border-b border-border-color shadow-sm z-30">
      <div
        class="container mx-auto px-4 py-3 flex items-center justify-between"
        style="max-width: unset"
      >
        <div class="flex items-center space-x-2">
          <h1 class="text-xl font-semibold text-gray-800">智能研究助理</h1>
          <span
            class="bg-blue-100 text-primary text-xs px-2 py-0.5 rounded-full"
            >多代理协作</span
          >
        </div>

        <div class="flex items-center space-x-4">
          <button
            id="export-btn"
            class="flex items-center text-gray-600 hover:text-primary transition-colors px-3 py-1.5 rounded-md hover:bg-blue-50"
          >
            <i class="fa fa-download mr-1.5"></i>
            <span>导出结果</span>
          </button>
          <button
            id="share-btn"
            class="flex items-center text-gray-600 hover:text-primary transition-colors px-3 py-1.5 rounded-md hover:bg-blue-50"
          >
            <i class="fa fa-share-alt mr-1.5"></i>
            <span>分享</span>
          </button>
          <button
            id="settings-btn"
            class="flex items-center text-gray-600 hover:text-primary transition-colors px-3 py-1.5 rounded-md hover:bg-blue-50"
          >
            <i class="fa fa-cog"></i>
          </button>
          <div class="h-8 w-8 rounded-full bg-gray-200 overflow-hidden">
            <img
              src="./images/avatar.jpg"
              alt="用户头像"
              class="h-full w-full object-cover"
            />
          </div>
        </div>
      </div>
    </header>

    <div class="flex flex-1 overflow-hidden">
      <!-- 左侧边栏: 30% 宽度 -->
      <aside
        class="w-[20%] bg-white border-r border-border-color flex flex-col overflow-hidden"
      >
        <!-- 查询历史记录 -->
        <div class="flex-1 overflow-y-auto scrollbar-hide">
          <div
            class="p-4 border-b border-border-color sticky top-0 bg-white z-10"
          >
            <h2 class="text-lg font-semibold mb-3 flex items-center">
              <i class="fa fa-history text-primary mr-2"></i>
              查询历史
            </h2>
            <div class="relative">
              <input
                type="text"
                placeholder="搜索历史..."
                class="w-full pl-9 pr-3 py-2 rounded-lg border border-border-color focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary transition-all"
              />
              <i
                class="fa fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"
              ></i>
            </div>
          </div>

          <div id="history-list" class="divide-y divide-border-color">
            <!-- 历史记录将通过JS动态生成 -->
          </div>
        </div>
      </aside>

      <!-- 主内容区: 70% 宽度 -->
      <main class="w-[50%] flex flex-col overflow-hidden">
        <!-- 代理状态可视化 -->
        <div class="p-4 border-b border-border-color">
          <h2 class="text-lg font-semibold mb-3 flex items-center">
            <i class="fa fa-users text-primary mr-2"></i>
            代理状态
          </h2>
          <div
            id="agent-status-container"
            class="grid grid-cols-1 gap-3"
            style="display: flex; overflow: auto"
          >
            <!-- 代理卡片将通过JS动态生成 -->
          </div>
        </div>

        <!-- 迭代过程可视化 -->
        <div
          class="p-4 border-b border-border-color overflow-y-auto scrollbar-hide"
          style="flex: 1"
        >
          <h2 class="text-lg font-semibold mb-3 flex items-center">
            <i class="fa fa-refresh text-primary mr-2"></i>
            迭代过程
          </h2>
          <div
            id="iteration-timeline"
            class="overflow-y-auto scrollbar-hide relative pl-10 space-y-4"
            style="height: calc(100% - 48px)"
          >
            <div class="timeline-connector"></div>
            <!-- 迭代时间线将通过JS动态生成 -->
          </div>
        </div>
        <!-- 查询输入区 -->
        <div class="p-4 border-b border-border-color bg-white">
          <h2 class="text-lg font-semibold mb-3 flex items-center">
            <i class="fa fa-search text-primary mr-2"></i>
            研究查询
          </h2>
          <div class="mb-3">
            <textarea
              id="query-input"
              rows="3"
              placeholder="请输入您的研究问题...例如：分析2023年人工智能领域的重要突破，并评估其对医疗行业的潜在影响"
              class="w-full px-4 py-3 rounded-lg border border-border-color focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary transition-all resize-none"
            ></textarea>
            <div
              class="flex justify-between items-center mt-2 text-sm text-gray-500"
            >                             
              <div class="flex space-x-1" style="align-items: center;">
                <span id="char-count">0 字符</span>
                <button
                  class="p-1.5 rounded hover:bg-gray-100 text-gray-600"
                  title="格式化"
                >
                  <i class="fa fa-paragraph"></i>
                </button>
                <button
                  id="voice-input-btn"
                  class="p-1.5 rounded hover:bg-gray-100 text-gray-600"
                  title="语音输入"
                >
                  <i class="fa fa-microphone"></i>
                </button>
                <button
                  class="p-1.5 rounded hover:bg-gray-100 text-gray-600"
                  title="上传文件"
                >
                  <i class="fa fa-paperclip"></i>
                </button>
              </div>
              <div class="bg-gray-50 p-3 rounded-lg">
                <div class="flex flex-wrap gap-2">
                  <div class="flex items-center space-x-1">
                    <span class="text-sm text-gray-600">迭代次数:</span>
                    <select
                      class="text-sm border border-border-color rounded px-2 py-1 focus:outline-none focus:ring-1 focus:ring-primary"
                    >
                      <option>3</option>
                      <option selected>5</option>
                      <option>10</option>
                    </select>
                  </div>
                  <div class="flex items-center space-x-1">
                    <span class="text-sm text-gray-600">详细程度:</span>
                    <select
                      class="text-sm border border-border-color rounded px-2 py-1 focus:outline-none focus:ring-1 focus:ring-primary"
                    >
                      <option>简要</option>
                      <option selected>中等</option>
                      <option>详细</option>
                    </select>
                  </div>
                  <div class="flex items-center space-x-1">
                    <span class="text-sm text-gray-600">输出格式:</span>
                    <select
                      class="text-sm border border-border-color rounded px-2 py-1 focus:outline-none focus:ring-1 focus:ring-primary"
                    >
                      <option selected>Markdown</option>
                      <option>纯文本</option>
                      <option>结构化数据</option>
                    </select>
                  </div>
                </div>
              </div>  
              <button
              id="submit-query"
              class="bg-primary hover:bg-primary/90 text-white font-medium py-2.5 px-4 rounded-lg transition-all flex items-center justify-center space-x-2"
            >
              <span>开始分析</span>
              <i class="fa fa-arrow-right"></i>
            </button>
            </div>
          </div>
        </div>
      </main>

      <!-- 实时输出显示 -->
      <div
        class="w-[30%] flex flex-col overflow-hidden flex-1 overflow-y-auto p-4 bg-gray-50"
      >
        <div
          id="output-container"
          class="bg-white rounded-xl shadow-sm p-6"
          style="height: 100%"
        >
          <div class="flex justify-between items-center mb-4">
            <h2 class="text-lg font-semibold flex items-center">
              <i class="fa fa-file-text-o text-primary mr-2"></i>
              研究结果
            </h2>
            <div class="flex space-x-2">
              <button
                id="copy-btn"
                class="text-gray-500 hover:text-primary text-sm px-2 py-1 rounded hover:bg-gray-100"
              >
                <i class="fa fa-copy mr-1"></i>复制
              </button>
              <button
                id="fullscreen-btn"
                class="text-gray-500 hover:text-primary text-sm px-2 py-1 rounded hover:bg-gray-100"
              >
                <i class="fa fa-expand mr-1"></i>全屏
              </button>
            </div>
          </div>

          <div
            id="streaming-output"
            class="font-sans text-gray-800 leading-relaxed"
          >
            <div class="text-center py-10 text-gray-500">
              <i class="fa fa-lightbulb-o text-4xl mb-3 text-gray-300"></i>
              <p>输入您的研究问题并提交，智能代理将开始协作分析</p>
            </div>
          </div>
        </div>

        <!-- 多模态内容展示 -->
        <div id="multimodal-content" class="space-y-6">
          <!-- 多模态内容将通过JS动态生成 -->
        </div>
      </div>
    </div>

    <!-- 设置菜单模态框 -->
    <div
      id="settings-modal"
      class="fixed inset-0 bg-black/50 z-50 hidden items-center justify-center"
    >
      <div
        class="bg-white rounded-xl w-full max-w-md p-6 shadow-xl transform transition-all"
      >
        <div class="flex justify-between items-center mb-4">
          <h3 class="text-lg font-semibold">设置</h3>
          <button id="close-settings" class="text-gray-500 hover:text-gray-700">
            <i class="fa fa-times"></i>
          </button>
        </div>

        <div class="space-y-4">
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1"
              >打字机速度</label
            >
            <input
              type="range"
              min="10"
              max="100"
              value="30"
              class="w-full accent-primary"
              id="type-speed"
            />
          </div>

          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1"
              >自动滚动</label
            >
            <div class="flex items-center">
              <input
                type="checkbox"
                checked
                id="auto-scroll"
                class="mr-2 accent-primary"
              />
              <label for="auto-scroll" class="text-sm text-gray-600"
                >结果输出时自动滚动到底部</label
              >
            </div>
          </div>

          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1"
              >默认输出格式</label
            >
            <select
              class="w-full border border-border-color rounded px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary"
            >
              <option selected>Markdown</option>
              <option>纯文本</option>
              <option>结构化数据</option>
            </select>
          </div>

          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1"
              >主题</label
            >
            <div class="flex space-x-2">
              <button
                class="px-3 py-1 border border-border-color rounded bg-gray-100 text-sm"
              >
                浅色
              </button>
              <button
                class="px-3 py-1 border border-border-color rounded text-sm"
              >
                深色
              </button>
              <button
                class="px-3 py-1 border border-border-color rounded text-sm"
              >
                跟随系统
              </button>
            </div>
          </div>
        </div>

        <div class="mt-6 flex justify-end">
          <button
            id="save-settings"
            class="bg-primary text-white px-4 py-2 rounded-lg hover:bg-primary/90 transition-colors"
          >
            保存设置
          </button>
        </div>
      </div>
    </div>

    <script>
      // 模拟数据
      const agents = [
        {
          id: 1,
          name: "协调员",
          role: "任务分配与进度监控",
          status: "idle",
          progress: 0,
          currentTask: "等待任务分配",
          color: "primary-agent",
        },
        {
          id: 2,
          name: "搜索专家",
          role: "文献与数据收集",
          status: "idle",
          progress: 0,
          currentTask: "等待任务分配",
          color: "research-agent",
        },
        {
          id: 3,
          name: "分析专家",
          role: "数据解读与模式识别",
          status: "idle",
          progress: 0,
          currentTask: "等待任务分配",
          color: "analysis-agent",
        },
        {
          id: 4,
          name: "质量保证",
          role: "结果验证与准确性检查",
          status: "idle",
          progress: 0,
          currentTask: "等待任务分配",
          color: "qa-agent",
        },
        {
          id: 5,
          name: "写作专家",
          role: "内容组织与呈现优化",
          status: "idle",
          progress: 0,
          currentTask: "等待任务分配",
          color: "writing-agent",
        },
      ];

      const iterations = [
        // 将在研究过程中动态生成
      ];

      const queryHistory = [
        {
          id: 1,
          query: "分析2022年可再生能源领域的技术突破及其市场影响",
          timestamp: "2023-05-15 14:30",
          duration: "4分25秒",
          resultPreview:
            "2022年可再生能源领域出现了多项重要技术突破，包括高效光伏电池、先进储能系统...",
          agentsInvolved: 5,
        },
        {
          id: 2,
          query: "探索量子计算在药物研发中的应用现状与未来潜力",
          timestamp: "2023-05-10 09:15",
          duration: "6分10秒",
          resultPreview:
            "量子计算正逐渐成为药物研发领域的新工具，其强大的计算能力能够模拟复杂的分子结构...",
          agentsInvolved: 4,
        },
        {
          id: 3,
          query: "总结过去五年全球教育科技投资趋势与热点领域",
          timestamp: "2023-05-05 16:45",
          duration: "3分50秒",
          resultPreview:
            "过去五年，全球教育科技投资呈现稳步增长趋势，特别是在在线学习平台、自适应学习系统...",
          agentsInvolved: 3,
        },
      ];

      // DOM元素引用
      const agentStatusContainer = document.getElementById(
        "agent-status-container"
      );
      const iterationTimeline = document.getElementById("iteration-timeline");
      const historyList = document.getElementById("history-list");
      const queryInput = document.getElementById("query-input");
      const charCount = document.getElementById("char-count");
      const submitQueryBtn = document.getElementById("submit-query");
      const streamingOutput = document.getElementById("streaming-output");
      const multimodalContent = document.getElementById("multimodal-content");
      const settingsBtn = document.getElementById("settings-btn");
      const settingsModal = document.getElementById("settings-modal");
      const closeSettingsBtn = document.getElementById("close-settings");
      const saveSettingsBtn = document.getElementById("save-settings");
      const exportBtn = document.getElementById("export-btn");
      const stageOutputContainer = document.getElementById(
        "stage-output-container"
      );
      const stageTitle = document.getElementById("stage-title");
      const stageContent = document.getElementById("stage-content");
      const closeStageOutputBtn = document.getElementById("close-stage-output");
      // 复制和全屏相关元素
      const copyBtn = document.getElementById("copy-btn");
      const fullscreenBtn = document.getElementById("fullscreen-btn");
      const outputContainer = document.getElementById("output-container");
      // 获取语音输入按钮
      const voiceInputBtn = document.querySelector('[title="语音输入"]');
      let isFullscreen = false;

      // 初始化界面
      function initializeUI() {
        renderAgentStatuses();
        renderHistoryList();

        // 字符计数
        queryInput.addEventListener("input", () => {
          charCount.textContent = `${queryInput.value.length} 字符`;
        });

        // 提交查询
        submitQueryBtn.addEventListener("click", startResearch);

        // 语音输入功能
        if (voiceInputBtn && "webkitSpeechRecognition" in window) {
          const recognition = new webkitSpeechRecognition();
          recognition.continuous = false;
          recognition.interimResults = true;
          recognition.lang = "zh-CN";

          recognition.onresult = function (event) {
            let finalTranscript = "";
            for (let i = event.resultIndex; i < event.results.length; i++) {
              if (event.results[i].isFinal) {
                finalTranscript += event.results[i][0].transcript;
              }
            }
            queryInput.value += finalTranscript;
            charCount.textContent = `${queryInput.value.length} 字符`;
          };

          recognition.onerror = function (event) {
            showNotification("语音识别出错: " + event.error, "error");
            voiceInputBtn.innerHTML = '<i class="fa fa-microphone"></i>';
            voiceInputBtn.classList.remove("bg-red-100", "text-red-600");
          };

          recognition.onend = function () {
            voiceInputBtn.innerHTML = '<i class="fa fa-microphone"></i>';
            voiceInputBtn.classList.remove("bg-blue-100", "text-blue-600");
          };

          voiceInputBtn.addEventListener("click", function () {
            if (recognition.state === "listening") {
              recognition.stop();
              voiceInputBtn.innerHTML = '<i class="fa fa-microphone"></i>';
              voiceInputBtn.classList.remove("bg-blue-100", "text-blue-600");
            } else {
              try {
                // 先检查是否在安全上下文中运行（HTTPS或localhost）
                if (location.protocol !== 'https:' && location.hostname !== 'localhost' && location.hostname !== '127.0.0.1') {
                  showNotification("语音输入功能需要在安全环境中运行（HTTPS或localhost）", "error");
                  return;
                }

                // 检查是否已获得麦克风权限
                if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
                  navigator.mediaDevices.getUserMedia({ audio: true })
                    .then(function(stream) {
                      // 成功获取麦克风权限，停止音频流并开始语音识别
                      stream.getTracks().forEach(track => track.stop());
                      try {
                        recognition.start();
                        voiceInputBtn.innerHTML = '<i class="fa fa-microphone-slash"></i>';
                        voiceInputBtn.classList.add("bg-blue-100", "text-blue-600");
                      } catch (err) {
                        console.error("启动语音识别失败:", err);
                        showNotification("无法启动语音识别: " + err.message, "error");
                      }
                    })
                    .catch(function(err) {
                      // 无法获取麦克风权限
                      console.error("麦克风权限被拒绝:", err);
                      // 检查是否是HTTPS环境下的权限问题
                      if (location.protocol === 'https:') {
                        showNotification("麦克风权限被拒绝。解决方法：1）点击地址栏中的锁图标并允许麦克风访问；2）在浏览器设置中手动允许麦克风权限；3）刷新页面重试", "error");
                      } else {
                        showNotification("麦克风权限被拒绝。解决方法：1）检查浏览器地址栏是否有麦克风权限图标并允许访问；2）在浏览器设置中手动允许麦克风权限；3）刷新页面重试", "error");
                      }
                    });
                } else {
                  // 浏览器不支持mediaDevices API，直接尝试启动语音识别
                  try {
                    recognition.start();
                    voiceInputBtn.innerHTML = '<i class="fa fa-microphone-slash"></i>';
                    voiceInputBtn.classList.add("bg-blue-100", "text-blue-600");
                  } catch (err) {
                    console.error("启动语音识别失败:", err);
                    if (err.name === 'NotAllowedError') {
                      // 检查是否是HTTPS环境下的权限问题
                      if (location.protocol === 'https:') {
                        showNotification("麦克风权限被拒绝。解决方法：1）点击地址栏中的锁图标并允许麦克风访问；2）在浏览器设置中手动允许麦克风权限；3）刷新页面重试", "error");
                      } else {
                        showNotification("麦克风权限被拒绝。解决方法：1）检查浏览器地址栏是否有麦克风权限图标并允许访问；2）在浏览器设置中手动允许麦克风权限；3）刷新页面重试", "error");
                      }
                    } else {
                      showNotification("无法启动语音识别: " + err.message, "error");
                    }
                  }
                }
              } catch (err) {
                console.error("语音识别初始化错误:", err);
                if (err.name === 'NotAllowedError') {
                  // 检查是否是HTTPS环境下的权限问题
                  if (location.protocol === 'https:') {
                    showNotification("麦克风权限被拒绝。解决方法：1）点击地址栏中的锁图标并允许麦克风访问；2）在浏览器设置中手动允许麦克风权限；3）刷新页面重试", "error");
                  } else {
                    showNotification("麦克风权限被拒绝。解决方法：1）检查浏览器地址栏是否有麦克风权限图标并允许访问；2）在浏览器设置中手动允许麦克风权限；3）刷新页面重试", "error");
                  }
                } else {
                  showNotification("语音识别功能初始化失败: " + err.message, "error");
                }
              }
            }
          });
        } else if (voiceInputBtn) {
          // 如果浏览器不支持语音识别，隐藏按钮或显示提示
          voiceInputBtn.style.display = "none";
        }

        // 设置模态框
        settingsBtn.addEventListener("click", () => {
          settingsModal.classList.remove("hidden");
          settingsModal.classList.add("flex");
        });

        closeSettingsBtn.addEventListener("click", () => {
          settingsModal.classList.add("hidden");
          settingsModal.classList.remove("flex");
        });

        saveSettingsBtn.addEventListener("click", () => {
          // 保存设置逻辑
          settingsModal.classList.add("hidden");
          settingsModal.classList.remove("flex");

          // 显示保存成功提示
          showNotification("设置已保存");
        });

        // 关闭阶段输出面板
        closeStageOutputBtn?.addEventListener("click", () => {
          stageOutputContainer.classList.add("hidden");
          stageOutputContainer.classList.remove("flex", "flex-col");
        });

        // 复制功能
        copyBtn.addEventListener("click", copyResults);

        // 全屏切换
        fullscreenBtn.addEventListener("click", toggleFullscreen);

        // 导出按钮
        exportBtn.addEventListener("click", () => {
          if (streamingOutput.innerHTML.includes("lightbulb-o")) {
            showNotification("没有可导出的研究结果", "warning");
            return;
          }
          showNotification("研究结果正在导出...");
          // 模拟导出延迟
          setTimeout(() => {
            showNotification("研究结果已成功导出");
          }, 1500);
        });
      }

      // 渲染代理状态
      function renderAgentStatuses() {
        agentStatusContainer.innerHTML = "";

        agents.forEach((agent) => {
          let statusIcon, statusClass, statusText;

          switch (agent.status) {
            case "idle":
              statusIcon = "fa-circle-o";
              statusClass = `bg-green-100 text-green-600`;
              statusText = "空闲";
              break;
            case "working":
              statusIcon = "fa-spinner fa-spin";
              statusClass = `bg-yellow-100 text-yellow-600 agent-pulse`;
              statusText = "工作中";
              break;
            case "completed":
              statusIcon = "fa-check";
              statusClass = `bg-blue-100 text-blue-600`;
              statusText = "已完成";
              break;
            case "error":
              statusIcon = "fa-exclamation-triangle";
              statusClass = `bg-red-100 text-red-600`;
              statusText = "错误";
              break;
          }

          const agentCard = document.createElement("div");
          agentCard.style.minWidth = "246px";
          agentCard.className = `agent-card p-3 rounded-lg border border-border-color shadow-sm bg-white`;
          agentCard.innerHTML = `
                    <div class="flex justify-between items-start mb-2">
                        <div class="flex items-center">
                            <div class="w-8 h-8 rounded-full bg-${
                              agent.color
                            }/10 flex items-center justify-center text-${
            agent.color
          } mr-2">
                                <i class="fa fa-user"></i>
                            </div>
                            <div>
                                <h3 class="font-medium text-gray-800">${
                                  agent.name
                                }</h3>
                                <p class="text-xs text-gray-500">${
                                  agent.role
                                }</p>
                            </div>
                        </div>
                        <span class="px-2 py-0.5 rounded-full text-xs font-medium ${statusClass}" style="flex-shrink: 0;">
                            <i class="fa ${statusIcon} mr-1"></i>${statusText}
                        </span>
                    </div>
                    <p class="text-sm text-gray-600 mb-2 line-clamp-1">${
                      agent.currentTask
                    }</p>
                    ${
                      agent.status === "working"
                        ? `
                        <div class="w-full bg-gray-200 rounded-full h-1.5">
                            <div class="progress-bar bg-${agent.color} h-1.5 rounded-full" style="width: ${agent.progress}%"></div>
                        </div>
                    `
                        : ""
                    }
                `;

          agentStatusContainer.appendChild(agentCard);
        });
      }

      // 渲染历史记录
      function renderHistoryList() {
        historyList.innerHTML = "";

        queryHistory.forEach((history) => {
          const historyItem = document.createElement("div");
          historyItem.className =
            "p-4 hover:bg-gray-50 transition-colors cursor-pointer";
          historyItem.innerHTML = `
                    <div class="flex justify-between items-start mb-2">
                        <h3 class="font-medium text-gray-800 line-clamp-1">${history.query}</h3>
                        <button class="text-gray-400 hover:text-primary">
                            <i class="fa fa-ellipsis-v"></i>
                        </button>
                    </div>
                    <p class="text-sm text-gray-600 line-clamp-2 mb-2">${history.resultPreview}</p>
                    <div class="flex justify-between items-center text-xs text-gray-500">
                        <span>${history.timestamp}</span>
                        <div class="flex items-center">
                            <i class="fa fa-clock-o mr-1"></i>
                            <span>${history.duration}</span>
                            <span class="mx-2">•</span>
                            <i class="fa fa-users mr-1"></i>
                            <span>${history.agentsInvolved}个代理</span>
                        </div>
                    </div>
                `;

          // 添加回放功能
          historyItem.addEventListener("click", () => {
            queryInput.value = history.query;
            charCount.textContent = `${history.query.length} 字符`;
            showNotification('已加载历史查询，点击"开始研究分析"重新运行');
          });

          historyList.appendChild(historyItem);
        });
      }

      // 添加迭代记录
      function addIteration(
        iterationNumber,
        status,
        agentsInvolved,
        description
      ) {
        const now = new Date();
        const timeString = `${now.getHours().toString().padStart(2, "0")}:${now
          .getMinutes()
          .toString()
          .padStart(2, "0")}:${now.getSeconds().toString().padStart(2, "0")}`;

        const iteration = {
          id: `iter-${iterationNumber}`,
          number: iterationNumber,
          status,
          agentsInvolved,
          startTime: timeString,
          description,
        };

        iterations.push(iteration);

        const iterationItem = document.createElement("div");
        iterationItem.id = iteration.id;
        iterationItem.className = "relative z-10 slide-in";

        let statusIcon, statusClass;

        switch (status) {
          case "running":
            statusIcon = "fa-spinner fa-spin";
            statusClass = "bg-yellow-100 text-yellow-600";
            break;
          case "completed":
            statusIcon = "fa-check";
            statusClass = "bg-green-100 text-green-600";
            break;
          case "skipped":
            statusIcon = "fa-times";
            statusClass = "bg-gray-100 text-gray-600";
            break;
        }

        iterationItem.innerHTML = `
                <div class="absolute left-0 top-0 -translate-x-[calc(100%+16px)] w-5 h-5 rounded-full bg-white border-2 ${statusClass
                  .replace("text-", "border-")
                  .replace("bg-", "bg-")} flex items-center justify-center">
                    <i class="fa ${statusIcon} ${
          statusClass.split(" ")[1]
        }" style="font-size: 12px;"></i>
                </div>
                <div class="bg-white p-3 rounded-lg border border-border-color shadow-sm">
                    <div class="flex justify-between items-center mb-1">
                        <h4 class="font-medium text-gray-800">迭代 #${iterationNumber}</h4>
                        <span class="text-xs text-gray-500">${timeString}</span>
                    </div>
                    <p class="text-sm text-gray-600 mb-2">${description}</p>
                    <div class="flex flex-wrap gap-1">
                        ${agentsInvolved
                          .map((agentId) => {
                            const agent = agents.find((a) => a.id === agentId);
                            return `
                                <span class="text-xs px-2 py-0.5 rounded-full bg-${agent.color}/10 text-${agent.color}">
                                    ${agent.name}
                                </span>
                            `;
                          })
                          .join("")}
                    </div>
                </div>
            `;

        iterationTimeline.appendChild(iterationItem);

        // 滚动到底部
        const timelineContainer = iterationTimeline.parentElement;
        timelineContainer.scrollTop = timelineContainer.scrollHeight;
      }

      // 打字机效果
      function typeWriterEffect(text, element, speed = 30, callback) {
        let i = 0;
        element.innerHTML = "";

        function type() {
          if (i < text.length) {
            // 处理换行
            if (text.charAt(i) === "\n") {
              element.innerHTML += "<br>";
            } else {
              element.innerHTML += text.charAt(i);
            }
            i++;
            setTimeout(type, speed);

            // 自动滚动
            if (document.getElementById("auto-scroll").checked) {
              element.scrollTop = element.scrollHeight;
            }
          } else if (callback) {
            callback();
          }
        }

        type();
      }

      // 更新代理状态
      function updateAgentStatus(
        agentId,
        status,
        progress = 0,
        currentTask = ""
      ) {
        const agent = agents.find((a) => a.id === agentId);
        if (agent) {
          agent.status = status;
          agent.progress = progress;
          if (currentTask) agent.currentTask = currentTask;
          renderAgentStatuses();
        }
      }

      // 显示通知
      function showNotification(message, type = "success") {
        // 检查是否已有通知
        const existingNotification = document.querySelector(".notification");
        if (existingNotification) {
          existingNotification.remove();
        }

        const notification = document.createElement("div");
        notification.className = `notification fixed bottom-4 right-4 px-4 py-3 rounded-lg shadow-lg z-50 flex items-center space-x-2 transition-all transform translate-y-0 opacity-100`;

        let bgColor, icon;
        switch (type) {
          case "success":
            bgColor = "bg-green-50 text-green-800 border border-green-200";
            icon = "fa-check-circle";
            break;
          case "warning":
            bgColor = "bg-yellow-50 text-yellow-800 border border-yellow-200";
            icon = "fa-exclamation-circle";
            break;
          case "error":
            bgColor = "bg-red-50 text-red-800 border border-red-200";
            icon = "fa-times-circle";
            break;
          default:
            bgColor = "bg-blue-50 text-blue-800 border border-blue-200";
            icon = "fa-info-circle";
        }

        notification.classList.add(...bgColor.split(" "));
        notification.innerHTML = `
                <i class="fa ${icon}"></i>
                <span>${message}</span>
            `;

        document.body.appendChild(notification);

        // 3秒后自动消失
        setTimeout(() => {
          notification.classList.add("opacity-0", "translate-y-4");
          setTimeout(() => {
            notification.remove();
          }, 300);
        }, 3000);
      }

      // 全屏切换功能
      function toggleFullscreen() {
        isFullscreen = !isFullscreen;

        if (isFullscreen) {
          // 进入全屏
          outputContainer.classList.add("fullscreen");
          fullscreenBtn.innerHTML =
            '<i class="fa fa-compress mr-1"></i>退出全屏';
          // 滚动到顶部
          outputContainer.scrollTop = 0;
        } else {
          // 退出全屏
          outputContainer.classList.remove("fullscreen");
          fullscreenBtn.innerHTML = '<i class="fa fa-expand mr-1"></i>全屏';
        }
      }

      // 语音输入功能
      function initVoiceInput() {
        // 检查浏览器是否支持语音识别
        const SpeechRecognition =
          window.SpeechRecognition || window.webkitSpeechRecognition;

        if (voiceInputBtn && SpeechRecognition) {
          const recognition = new SpeechRecognition();
          recognition.continuous = false;
          recognition.interimResults = true;
          recognition.lang = "zh-CN";

          recognition.onresult = function (event) {
            let finalTranscript = "";
            for (let i = event.resultIndex; i < event.results.length; i++) {
              if (event.results[i].isFinal) {
                finalTranscript += event.results[i][0].transcript;
              }
            }
            queryInput.value += finalTranscript;
            charCount.textContent = `${queryInput.value.length} 字符`;
            voiceInputBtn.innerHTML = '<i class="fa fa-microphone"></i>';
            voiceInputBtn.classList.remove("bg-blue-100", "text-blue-600");
          };

          recognition.onerror = function (event) {
            console.error("语音识别错误:", event.error);
            let errorMsg = "语音识别出错";
            switch(event.error) {
              case "not-allowed":
              case "permission-denied":
                errorMsg = "麦克风权限被拒绝。解决方法：1）检查浏览器地址栏是否有麦克风权限图标并允许访问；2）在浏览器设置中手动允许麦克风权限；3）刷新页面重试";
                break;
              case "no-speech":
                errorMsg = "未检测到语音，请重试";
                break;
              case "audio-capture":
                errorMsg = "无法访问麦克风设备";
                break;
              case "network":
                errorMsg = "网络错误，请检查网络连接";
                break;
              case "aborted":
                errorMsg = "语音识别被中断";
                break;
              case "language-not-supported":
                errorMsg = "不支持所选语言";
                break;
              default:
                errorMsg = "语音识别出错: " + event.error;
            }
            showNotification(errorMsg, "error");
            voiceInputBtn.innerHTML = '<i class="fa fa-microphone"></i>';
            voiceInputBtn.classList.remove("bg-red-100", "text-red-600");
            voiceInputBtn.classList.remove("bg-blue-100", "text-blue-600");
          };

          recognition.onend = function () {
            voiceInputBtn.innerHTML = '<i class="fa fa-microphone"></i>';
            voiceInputBtn.classList.remove("bg-blue-100", "text-blue-600");
          };

          voiceInputBtn.addEventListener("click", function () {
            if (recognition.state === "listening") {
              recognition.stop();
              voiceInputBtn.innerHTML = '<i class="fa fa-microphone"></i>';
              voiceInputBtn.classList.remove("bg-blue-100", "text-blue-600");
            } else {
              try {
                // 先检查是否在安全上下文中运行（HTTPS或localhost）
                if (location.protocol !== 'https:' && location.hostname !== 'localhost' && location.hostname !== '127.0.0.1') {
                  showNotification("语音输入功能需要在安全环境中运行（HTTPS或localhost）", "error");
                  return;
                }

                // 检查是否已获得麦克风权限
                if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
                  navigator.mediaDevices.getUserMedia({ audio: true })
                    .then(function(stream) {
                      // 成功获取麦克风权限，停止音频流并开始语音识别
                      stream.getTracks().forEach(track => track.stop());
                      try {
                        recognition.start();
                        voiceInputBtn.innerHTML = '<i class="fa fa-microphone-slash"></i>';
                        voiceInputBtn.classList.add("bg-blue-100", "text-blue-600");
                      } catch (err) {
                        console.error("启动语音识别失败:", err);
                        showNotification("无法启动语音识别: " + err.message, "error");
                      }
                    })
                    .catch(function(err) {
                      // 无法获取麦克风权限
                      console.error("麦克风权限被拒绝:", err);
                      showNotification("需要麦克风权限才能使用语音输入功能。请确保：1）已连接麦克风设备；2）在浏览器设置中允许访问麦克风；3）刷新页面重试", "error");
                    });
                } else {
                  // 浏览器不支持mediaDevices API，直接尝试启动语音识别
                  try {
                    recognition.start();
                    voiceInputBtn.innerHTML = '<i class="fa fa-microphone-slash"></i>';
                    voiceInputBtn.classList.add("bg-blue-100", "text-blue-600");
                  } catch (err) {
                    console.error("启动语音识别失败:", err);
                    showNotification("无法启动语音识别: " + err.message, "error");
                  }
                }
              } catch (err) {
                console.error("语音识别初始化错误:", err);
                showNotification("语音识别功能初始化失败: " + err.message, "error");
              }
            }
          });
        } else if (voiceInputBtn) {
          // 添加title提示信息
          voiceInputBtn.title = "浏览器不支持语音输入";
          voiceInputBtn.classList.add("opacity-50");
          
          // 添加点击事件，提示用户浏览器不支持
          voiceInputBtn.addEventListener("click", function() {
            showNotification("您的浏览器不支持语音输入功能。请使用Chrome、Edge等现代浏览器。", "error");
          });
        }
      }

      // 复制功能
      function copyResults() {
        // 获取研究结果文本内容
        const textToCopy =
          streamingOutput.innerText || streamingOutput.textContent;

        // 使用 Clipboard API 复制文本
        navigator.clipboard
          .writeText(textToCopy)
          .then(() => {
            showNotification("研究结果已复制到剪贴板");
          })
          .catch((err) => {
            // 如果 Clipboard API 不可用，使用备选方案
            const textArea = document.createElement("textarea");
            textArea.value = textToCopy;
            document.body.appendChild(textArea);
            textArea.select();
            try {
              document.execCommand("copy");
              showNotification("研究结果已复制到剪贴板");
            } catch (error) {
              showNotification("复制失败，请手动选择复制", "error");
            }
            document.body.removeChild(textArea);
          });
      }

      // 添加多模态内容
      function addMultimodalContent(type, data) {
        const contentItem = document.createElement("div");
        contentItem.className = "bg-white rounded-xl shadow-sm p-6 slide-in";

        switch (type) {
          case "chart":
            contentItem.innerHTML = `
                        <h3 class="text-lg font-semibold mb-4 flex items-center">
                            <i class="fa fa-bar-chart text-primary mr-2"></i>
                            数据分析图表
                        </h3>
                        <div class="h-64">
                            <canvas id="data-chart"></canvas>
                        </div>
                    `;
            multimodalContent.appendChild(contentItem);

            // 创建图表
            const ctx = document.getElementById("data-chart").getContext("2d");
            new Chart(ctx, data);
            break;

          case "image":
            contentItem.innerHTML = `
                        <h3 class="text-lg font-semibold mb-4 flex items-center">
                            <i class="fa fa-image text-primary mr-2"></i>
                            概念示意图
                        </h3>
                        <div class="rounded-lg overflow-hidden border border-border-color">
                            <img src="${data.url}" alt="${data.alt}" class="w-full h-auto object-cover">
                        </div>
                        <p class="text-sm text-gray-500 mt-2 italic">${data.caption}</p>
                    `;
            multimodalContent.appendChild(contentItem);
            break;

          case "table":
            let tableRows = "";
            data.rows.forEach((row) => {
              let cells = "";
              row.forEach((cell) => {
                cells += `<td class="border border-gray-200 px-4 py-2 text-sm">${cell}</td>`;
              });
              tableRows += `<tr>${cells}</tr>`;
            });

            contentItem.innerHTML = `
                        <h3 class="text-lg font-semibold mb-4 flex items-center">
                            <i class="fa fa-table text-primary mr-2"></i>
                            比较数据表格
                        </h3>
                        <div class="overflow-x-auto">
                            <table class="min-w-full border border-gray-200">
                                <thead>
                                    <tr class="bg-gray-50">
                                        ${data.headers
                                          .map(
                                            (header) => `
                                            <th class="border border-gray-200 px-4 py-2 text-left text-sm font-medium text-gray-700">${header}</th>
                                        `
                                          )
                                          .join("")}
                                    </tr>
                                </thead>
                                <tbody>
                                    ${tableRows}
                                </tbody>
                            </table>
                        </div>
                    `;
            multimodalContent.appendChild(contentItem);
            break;
        }
      }

      // 开始研究流程
      function startResearch() {
        const query = queryInput.value.trim();
        if (!query) {
          showNotification("请输入研究问题", "warning");
          return;
        }

        // 重置界面
        streamingOutput.innerHTML = "";
        multimodalContent.innerHTML = "";
        iterationTimeline.innerHTML = '<div class="timeline-connector"></div>';
        iterations.length = 0;

        // 禁用提交按钮
        submitQueryBtn.disabled = true;
        submitQueryBtn.classList.add("opacity-70", "cursor-not-allowed");
        submitQueryBtn.innerHTML =
          '<i class="fa fa-spinner fa-spin mr-2"></i><span>研究进行中...</span>';

        // 更新所有代理为空闲状态
        agents.forEach((agent) => {
          agent.status = "idle";
          agent.progress = 0;
          agent.currentTask = "等待任务分配";
        });
        renderAgentStatuses();

        showNotification("研究开始，代理团队正在协作分析");

        // 研究流程模拟
        setTimeout(() => {
          // 迭代1: 问题分析与任务分配
          addIteration(1, "running", [1], "分析研究问题并分配任务给各代理");
          updateAgentStatus(1, "working", 30, "分析研究问题");

          setTimeout(() => {
            updateAgentStatus(1, "working", 70, "分配任务给各代理");

            setTimeout(() => {
              updateAgentStatus(1, "completed", 100, "任务分配完成");
              document.getElementById("iter-1").innerHTML = document
                .getElementById("iter-1")
                .innerHTML.replace("running", "completed")
                .replace("fa-spinner fa-spin", "fa-check")
                .replace(
                  "bg-yellow-100 text-yellow-600",
                  "bg-green-100 text-green-600"
                )
                .replace("border-yellow-600", "border-green-600");

              // 开始输出
              const introText = `# 关于"${query}"的研究分析\n\n我们的多代理研究团队已开始针对您的问题进行系统分析。以下是研究过程和结果的详细记录：\n\n`;

              typeWriterEffect(introText, streamingOutput, 10, () => {
                // 迭代2: 数据收集
                setTimeout(() => {
                  addIteration(2, "running", [2], "收集相关文献和数据");
                  updateAgentStatus(2, "working", 20, "搜索学术数据库");

                  setTimeout(() => {
                    updateAgentStatus(2, "working", 60, "筛选相关文献");

                    setTimeout(() => {
                      updateAgentStatus(2, "completed", 100, "数据收集完成");
                      document.getElementById("iter-2").innerHTML = document
                        .getElementById("iter-2")
                        .innerHTML.replace("running", "completed")
                        .replace("fa-spinner fa-spin", "fa-check")
                        .replace(
                          "bg-yellow-100 text-yellow-600",
                          "bg-green-100 text-green-600"
                        )
                        .replace("border-yellow-600", "border-green-600");

                      const dataCollectionText = `## 数据收集阶段\n\n搜索专家已完成相关文献和数据的收集工作，共检索到32篇相关学术论文，15份行业报告和8组统计数据集。主要来源包括：\n- 学术数据库（PubMed, IEEE Xplore, arXiv）\n- 行业分析报告（Gartner, McKinsey, IDC）\n- 政府和研究机构公开数据\n\n`;

                      typeWriterEffect(
                        dataCollectionText,
                        streamingOutput,
                        20,
                        () => {
                          // 迭代3: 数据分析
                          setTimeout(() => {
                            addIteration(
                              3,
                              "running",
                              [3],
                              "分析收集的数据和信息"
                            );
                            updateAgentStatus(3, "working", 30, "数据预处理");

                            setTimeout(() => {
                              updateAgentStatus(
                                3,
                                "working",
                                70,
                                "模式识别与趋势分析"
                              );

                              setTimeout(() => {
                                updateAgentStatus(
                                  3,
                                  "completed",
                                  100,
                                  "数据分析完成"
                                );
                                document.getElementById("iter-3").innerHTML =
                                  document
                                    .getElementById("iter-3")
                                    .innerHTML.replace("running", "completed")
                                    .replace("fa-spinner fa-spin", "fa-check")
                                    .replace(
                                      "bg-yellow-100 text-yellow-600",
                                      "bg-green-100 text-green-600"
                                    )
                                    .replace(
                                      "border-yellow-600",
                                      "border-green-600"
                                    );

                                const analysisText = `## 数据分析阶段\n\n分析专家对收集到的信息进行了系统分析，识别出以下几个关键趋势：\n\n1. **技术成熟度加速**：2023年AI领域的多项突破使技术成熟度曲线（Gartner Hype Cycle）提前了1-2年\n2. **跨学科融合**：人工智能与生物医学、材料科学等领域的交叉应用显著增加\n3. **监管框架发展**：全球范围内针对AI应用的监管政策数量同比增长40%\n\n特别是在医疗领域，AI技术的应用呈现出三个主要方向：诊断辅助、个性化治疗方案和药物研发加速。\n\n`;

                                typeWriterEffect(
                                  analysisText,
                                  streamingOutput,
                                  25,
                                  () => {
                                    // 添加图表
                                    setTimeout(() => {
                                      addMultimodalContent("chart", {
                                        type: "bar",
                                        data: {
                                          labels: [
                                            "2019",
                                            "2020",
                                            "2021",
                                            "2022",
                                            "2023",
                                          ],
                                          datasets: [
                                            {
                                              label: "AI医疗应用论文数量",
                                              data: [120, 190, 280, 450, 680],
                                              backgroundColor:
                                                "rgba(52, 152, 219, 0.6)",
                                              borderColor:
                                                "rgba(52, 152, 219, 1)",
                                              borderWidth: 1,
                                            },
                                          ],
                                        },
                                        options: {
                                          responsive: true,
                                          maintainAspectRatio: false,
                                          scales: {
                                            y: {
                                              beginAtZero: true,
                                            },
                                          },
                                        },
                                      });

                                      // 迭代4: 质量验证
                                      setTimeout(() => {
                                        addIteration(
                                          4,
                                          "running",
                                          [4],
                                          "验证分析结果的准确性"
                                        );
                                        updateAgentStatus(
                                          4,
                                          "working",
                                          50,
                                          "交叉验证数据来源"
                                        );

                                        setTimeout(() => {
                                          updateAgentStatus(
                                            4,
                                            "completed",
                                            100,
                                            "质量验证完成"
                                          );
                                          document.getElementById(
                                            "iter-4"
                                          ).innerHTML = document
                                            .getElementById("iter-4")
                                            .innerHTML.replace(
                                              "running",
                                              "completed"
                                            )
                                            .replace(
                                              "fa-spinner fa-spin",
                                              "fa-check"
                                            )
                                            .replace(
                                              "bg-yellow-100 text-yellow-600",
                                              "bg-green-100 text-green-600"
                                            )
                                            .replace(
                                              "border-yellow-600",
                                              "border-green-600"
                                            );

                                          const validationText = `## 质量验证阶段\n\n质量保证代理对分析结果进行了严格验证：\n- 数据来源可信度评分：4.7/5.0\n- 结果可重复性验证：92%一致\n- 潜在偏见评估：低风险\n\n验证过程中发现2处需要进一步澄清的数据点，已反馈给分析团队进行补充分析。\n\n`;

                                          typeWriterEffect(
                                            validationText,
                                            streamingOutput,
                                            20,
                                            () => {
                                              // 添加表格
                                              setTimeout(() => {
                                                addMultimodalContent("table", {
                                                  headers: [
                                                    "应用领域",
                                                    "技术成熟度",
                                                    "临床应用率",
                                                    "潜在风险",
                                                  ],
                                                  rows: [
                                                    [
                                                      "医学影像诊断",
                                                      "高",
                                                      "65%",
                                                      "中",
                                                    ],
                                                    [
                                                      "药物研发",
                                                      "中",
                                                      "30%",
                                                      "低",
                                                    ],
                                                    [
                                                      "个性化治疗",
                                                      "中低",
                                                      "15%",
                                                      "高",
                                                    ],
                                                    [
                                                      "医院管理",
                                                      "高",
                                                      "70%",
                                                      "低",
                                                    ],
                                                  ],
                                                });

                                                // 迭代5: 结果综合
                                                setTimeout(() => {
                                                  addIteration(
                                                    5,
                                                    "running",
                                                    [5, 1],
                                                    "综合结果并优化呈现方式"
                                                  );
                                                  updateAgentStatus(
                                                    5,
                                                    "working",
                                                    40,
                                                    "组织研究结果"
                                                  );
                                                  updateAgentStatus(
                                                    1,
                                                    "working",
                                                    50,
                                                    "协调最终输出"
                                                  );

                                                  setTimeout(() => {
                                                    updateAgentStatus(
                                                      5,
                                                      "working",
                                                      80,
                                                      "优化内容呈现"
                                                    );
                                                    updateAgentStatus(
                                                      1,
                                                      "working",
                                                      80,
                                                      "最终审核"
                                                    );

                                                    setTimeout(() => {
                                                      updateAgentStatus(
                                                        5,
                                                        "completed",
                                                        100,
                                                        "内容优化完成"
                                                      );
                                                      updateAgentStatus(
                                                        1,
                                                        "completed",
                                                        100,
                                                        "研究完成"
                                                      );
                                                      document.getElementById(
                                                        "iter-5"
                                                      ).innerHTML = document
                                                        .getElementById(
                                                          "iter-5"
                                                        )
                                                        .innerHTML.replace(
                                                          "running",
                                                          "completed"
                                                        )
                                                        .replace(
                                                          "fa-spinner fa-spin",
                                                          "fa-check"
                                                        )
                                                        .replace(
                                                          "bg-yellow-100 text-yellow-600",
                                                          "bg-green-100 text-green-600"
                                                        )
                                                        .replace(
                                                          "border-yellow-600",
                                                          "border-green-600"
                                                        );

                                                      const conclusionText = `## 结论与建议\n\n综合研究结果，2023年人工智能在医疗领域的应用呈现出以下关键结论：\n\n1. **诊断准确性提升**：AI辅助诊断系统在影像识别任务中已达到或超过人类专家水平，尤其在早期癌症检测方面准确率提升约23%\n\n2. **效率提升显著**：采用AI工作流程的医疗机构，平均诊断时间缩短40%，患者等待时间减少35%\n\n3. **成本效益平衡**：初期实施成本较高，但长期来看可降低医疗成本约15-20%\n\n4. **伦理与监管挑战**：数据隐私和算法透明度仍是主要障碍，需要更完善的政策框架\n\n### 建议\n- 医疗机构应采取渐进式实施策略，优先部署成熟度高的AI辅助诊断系统\n- 投资于医护人员的AI技能培训，促进人机协作而非替代\n- 参与行业标准制定，推动AI医疗应用的规范化和互操作性\n\n`;

                                                      typeWriterEffect(
                                                        conclusionText,
                                                        streamingOutput,
                                                        25,
                                                        () => {
                                                          // 添加总结图像
                                                          setTimeout(() => {
                                                            addMultimodalContent(
                                                              "image",
                                                              {
                                                                url: "https://picsum.photos/id/180/800/400",
                                                                alt: "AI在医疗领域应用的未来展望示意图",
                                                                caption:
                                                                  "AI医疗应用的发展路径与关键里程碑",
                                                              }
                                                            );

                                                            // 完成研究
                                                            setTimeout(() => {
                                                              const finalText = `## 研究完成\n\n本研究由5个专业代理协作完成，历时4分32秒。研究结果已通过质量验证，可作为决策参考。\n\n您可以：\n- 导出完整报告（PDF/Word/Markdown格式）\n- 针对特定部分进行深入研究\n- 修改查询条件重新分析`;

                                                              typeWriterEffect(
                                                                finalText,
                                                                streamingOutput,
                                                                20,
                                                                () => {
                                                                  // 恢复按钮状态
                                                                  submitQueryBtn.disabled = false;
                                                                  submitQueryBtn.classList.remove(
                                                                    "opacity-70",
                                                                    "cursor-not-allowed"
                                                                  );
                                                                  submitQueryBtn.innerHTML =
                                                                    '<span>开始研究分析</span><i class="fa fa-arrow-right ml-2"></i>';

                                                                  // 添加到历史记录
                                                                  const now =
                                                                    new Date();
                                                                  const timestamp = `${now.getFullYear()}-${(
                                                                    now.getMonth() +
                                                                    1
                                                                  )
                                                                    .toString()
                                                                    .padStart(
                                                                      2,
                                                                      "0"
                                                                    )}-${now
                                                                    .getDate()
                                                                    .toString()
                                                                    .padStart(
                                                                      2,
                                                                      "0"
                                                                    )} ${now
                                                                    .getHours()
                                                                    .toString()
                                                                    .padStart(
                                                                      2,
                                                                      "0"
                                                                    )}:${now
                                                                    .getMinutes()
                                                                    .toString()
                                                                    .padStart(
                                                                      2,
                                                                      "0"
                                                                    )}`;

                                                                  queryHistory.unshift(
                                                                    {
                                                                      id:
                                                                        queryHistory.length +
                                                                        1,
                                                                      query:
                                                                        query,
                                                                      timestamp:
                                                                        timestamp,
                                                                      duration:
                                                                        "4分32秒",
                                                                      resultPreview:
                                                                        conclusionText.substring(
                                                                          0,
                                                                          100
                                                                        ) +
                                                                        "...",
                                                                      agentsInvolved: 5,
                                                                    }
                                                                  );

                                                                  // 保持历史记录不超过10条
                                                                  if (
                                                                    queryHistory.length >
                                                                    10
                                                                  ) {
                                                                    queryHistory.pop();
                                                                  }

                                                                  renderHistoryList();

                                                                  showNotification(
                                                                    "研究已完成，结果已保存到历史记录"
                                                                  );
                                                                }
                                                              );
                                                            }, 1000);
                                                          }, 1000);
                                                        }
                                                      );
                                                    }, 2000);
                                                  }, 2000);
                                                }, 1000);
                                              }, 1000);
                                            }
                                          );
                                        }, 3000);
                                      }, 1000);
                                    }, 1000);
                                  }
                                );
                              }, 3000);
                            }, 2000);
                          }, 1000);
                        }
                      );
                    }, 2000);
                  }, 2000);
                }, 1000);
              });
            }, 2000);
          }, 2000);
        }, 500);
      }

      // 初始化界面
      document.addEventListener("DOMContentLoaded", initializeUI);
    </script>
  </body>
</html>
